package com.enzoism.springboot.dive.predicate;

import com.enzoism.springboot.dive.model.UsrModel;

import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class A01Predicate {
    public static void main(String[] args) {
        // 场景一：自定义过滤策略（后续尝试用Predicate书写）
        A01Predicate.groupingByDistinct();
    }

    /*
	 * 使用java8 stream groupingBy操作, 基于Distinct 去重数据
	 */
    public static void groupingByDistinct() {
        List<UsrModel> list = UsrModel.initList();
        list = list.stream().filter(distinctByKey(UsrModel :: getUsrId)).collect(Collectors.toList());;
        list.stream().forEach(item->{
            System.out.println("usrId = " + item.getUsrId());
        });
    }

    /**
     * 自定义重复key 规则：set有一个属性，添加成功返回1，没有成功返回0
     * @param keyExtractor
     * @return
     */
    private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Set<Object> seen = ConcurrentHashMap.newKeySet();
        return t -> seen.add(keyExtractor.apply(t));
    }}
